package cn.com.ghy.android.service;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.xmlpull.v1.XmlPullParser;

import android.util.Log;
import android.util.Xml;
import cn.com.ghy.android.exception.HttpRequestErrorException;
import cn.com.ghy.android.exception.HttpResponseNullException;
import cn.com.ghy.android.exception.HttpSserverErrorException;
import cn.com.ghy.android.util.CommonStatic;

/**
 * @软件著作权:金红叶纸业集团有限公司
 * @系统名称:SFA系统
 * @Description:与WebService链接服务器
 * @author wuz  @date 2011-8-16 08:08:02
 * @版本历史:v1.0
 * @Copyright:Copyright (c) 2011-2012 
 * @deprecated:新增与WebSevice链接,采用自定义封装和解析
 */

public class CustomHttpService {

	public static String callWS(final String url, final String methodName,
			Map<String, String> params) throws Exception {
		String result = null;
		String soap = soapXml(methodName, params);//简单对象访问协议(Simple Object Access Protocol)
		byte[] data = soap.getBytes();
		InputStream in = null;
		OutputStream outStream = null;
		try {
			URL urlHttp = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) urlHttp.openConnection();
			conn.setRequestMethod("POST");
			conn.setConnectTimeout(30 * 1000);
			conn.setDoOutput(true);//以后就可以使用conn.getOutputStream().write()
			conn.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
			conn.setRequestProperty("Content-Length", String.valueOf(data.length));
			outStream = conn.getOutputStream();
			outStream.write(data);
			outStream.flush();
			outStream.close();
			int statusCode = 0;
			statusCode = conn.getResponseCode();
			switch (statusCode) {
				case CommonStatic.HTTP_OK :
					in = conn.getInputStream();
					if (null != in) {
						result = parseXML(in, methodName);
						Log.d("wqqtag", result);
					}
					break;
				case CommonStatic.HTTP_SERVER_ERROR :
					throw new HttpSserverErrorException();
				case CommonStatic.HTTP_REQUEST_ERROR :
					throw new HttpRequestErrorException();
			}
			if (null == result || "".equals(result)) {
				throw new HttpResponseNullException(result);
			}
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				if (outStream != null) {
					outStream.close();
					outStream = null;
				}
				if (in != null) {
					in.close();
					in = null;
				}
			} catch (Exception e) {
				throw e;
			}
		}
		return result;
	}

	@SuppressWarnings("rawtypes")//粗类型
	private static String soapXml(String method, Map<String, String> map) {
		StringBuffer soapHeader = new StringBuffer();
		soapHeader.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		soapHeader.append("<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
		soapHeader.append("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" ");
		soapHeader.append("xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">");
		soapHeader.append("<soap12:Body>");
		soapHeader.append("<").append(method).append(" xmlns=\"").append(CommonStatic.NAMESPACE)
				.append("\">");
		if (map != null && !map.isEmpty()) {
			for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
				Map.Entry e = (Entry) it.next();
				soapHeader.append("<").append(e.getKey()).append(">");
				soapHeader.append(e.getValue());
				soapHeader.append("</").append(e.getKey()).append(">");
			}
		}
		soapHeader.append("</").append(method).append(">");
		soapHeader.append("</soap12:Body>");
		soapHeader.append("</soap12:Envelope>");
		System.out.println("soapHeader=======" + soapHeader);
		return soapHeader.toString();
	}

	public static String parseXML(InputStream in, String method) throws Exception {
		String result = "";
		StringBuffer sb = new StringBuffer();
		sb.append(method).append("Result");
		String tag = sb.toString();
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(in, "UTF-8");
		int type = parser.getEventType();

		while (type != XmlPullParser.END_DOCUMENT) {
			switch (type) {
				case XmlPullParser.START_DOCUMENT :
					break;

				case XmlPullParser.START_TAG :
					if (tag.equals(parser.getName())) {
						result = parser.nextText();
					}
					break;

				case XmlPullParser.END_TAG :
					break;
			}
			type = parser.next();
		}
		in.close();
		return result;
	}
}
